package com.y.fund.web.mem;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import com.y.fund.aacore.data.DataVo;
import com.y.fund.aacore.data.PaginationList;
import com.y.fund.aacore.enums.BoolVal;
import com.y.fund.aacore.vo.PagingVo;
import com.y.fund.domain.com.CO12Message;
import com.y.fund.domain.mem.MB13UserAccount;
import com.y.fund.domain.mem.MB13UserInfo;
import com.y.fund.handler.CurrLgnUserVo;
import com.y.fund.utils.MD5Util;
import com.y.fund.utils.SQLUtil;
import com.y.fund.utils.StrUtil;
import com.y.fund.web.BaseController;
import com.y.fund.web.aavo.com.IdsOptVo;
import com.y.fund.web.aavo.com.LgnUserVo;
import com.y.fund.web.aavo.mem.ChangePwdVo;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;

@ApiSort(62)
@RestController
@RequestMapping(value="api/my", produces = MediaType.APPLICATION_JSON_VALUE)
@Tag(name= "个人中心")
public class MyController extends BaseController{
	
    @GetMapping("detail")
    @Operation(summary = "个人用户详情")
    @ApiOperationSupport(order = 1)
    public DataVo detail(){
    	LgnUserVo luv = CurrLgnUserVo.Get();
    	if(null==luv || StrUtil.isBlankIncNullStr(luv.getUserId())) {
    		return DataVo.FailNotLgn();
    	}
    	MB13UserInfo user = commService.findObjById(MB13UserInfo.class, luv.getUserId());
    	if(null == user) {
    		return null;
    	}
    	Map<String, Object> myinfo = new LinkedHashMap<String, Object>();

    	myinfo.put("user", user);

    	return DataVo.Success(myinfo);
    }
    

    @PostMapping("chgpwd")
    @Operation(summary = "修改用户自己的登录密码")
    @ApiOperationSupport(order = 2)
    public DataVo userSave(@RequestBody ChangePwdVo chgPwd) throws Exception{
    	if(StrUtil.isBlankIncNullStr(chgPwd.getNewPwd())) {
        	return DataVo.FailNotData();
    	}
    	
    	LgnUserVo uvo = CurrLgnUserVo.Get();
    	MB13UserAccount user = commService.findObjById(MB13UserAccount.class, uvo.getUserId());
    	
    	if(null == user) {
        	return DataVo.FailNotLgn();
    	}
    	
		String pwd = MD5Util.encode(chgPwd.getOldPwd());
		if(null==pwd || !pwd.equals(user.getLgnPwd())) {
			return DataVo.Fail("Old password is error");
		}
    	
		MB13UserAccount updt = new MB13UserAccount();
    	updt.setId(user.getId());
    	updt.setLgnPwd(MD5Util.encode(chgPwd.getNewPwd()));
    	
    	if(commService.updtByIdIgnoreNull(updt)) {
        	return DataVo.Success(chgPwd.getNewPwd());
    	}else {
        	return DataVo.Fail("Save error");
    	}
    }

    @PostMapping("updt")
    @Operation(summary = "修改个人信息", description = "只修改非空字段")
    @ApiOperationSupport(order = 3)
    public DataVo updtUserIngroalNull(@RequestBody MB13UserAccount user) throws Exception{
    	LgnUserVo uvo = CurrLgnUserVo.Get();

    	user.setLgnPwd(null);
    	user.setId(uvo.getUserId());
    	
    	if(commService.updtByIdIgnoreNull(user)) {
        	return DataVo.Success(user.getId());
    	}else {
        	return DataVo.Fail("save error");
    	}
    }

    @GetMapping("msg/list")
    @Operation(summary = "根据当前用户分页查询消息记录")
    @ApiOperationSupport(order = 11)
    public DataVo myMsgList(CO12Message msg, PagingVo pvo){
    	LgnUserVo uvo = CurrLgnUserVo.Get();
    	if(null==uvo || StrUtil.isBlankIncNullStr(uvo.getUserId())) {
    		return DataVo.FailNotLgn();
    	}
    	msg.setOwnerId(uvo.getUserId());

    	PaginationList<CO12Message> pgList = commService.findPagingByExpLikeOrderCountById(msg, pvo, SQLUtil.CreateTimeDescOrder);
    	
    	return DataVo.Success(pgList);
    }

    @GetMapping("msg/unread/sum")
    @Operation(summary = "查找当前用户未读消息总数")
    @ApiOperationSupport(order = 11)
    public DataVo myMsgUnreadSum(){
    	LgnUserVo uvo = CurrLgnUserVo.Get();
    	if(null==uvo || StrUtil.isBlankIncNullStr(uvo.getUserId())) {
    		return DataVo.FailNotLgn();
    	}
    	CO12Message msg = new CO12Message(uvo.getUserId());
    	msg.setRead(BoolVal.No.getVal());
    	return DataVo.Success(commService.findSizeByExpCountById(msg));
    }

	@PostMapping(value = "msg/opt")
	@Operation(summary="根据ID对消息进行处理；根据opt的值区分： read:标记为已读；done:标记为待办已完成；del：删除", description = "根据opt的值区分： read:标记为已读；done:标记为待办已完成；del：删除")
    public DataVo opt(@RequestBody IdsOptVo idsOpt) throws Exception{
		if(null==idsOpt.getId() || idsOpt.getId().length<1) {
			return DataVo.FailMustParam("id");
		}
		if(StrUtil.isBlankIncNullStr(idsOpt.getOpt())) {
			return DataVo.FailMustParam("opt");
		}
		String userId = CurrLgnUserVo.Get().getUserId();
		
		CO12Message cmexp = new CO12Message();
		cmexp.setOwnerId(userId);
		
		List<CO12Message> msgs = commService.findListByExpAndIdIn(cmexp, Arrays.asList(idsOpt.getId()), null);

		Set<String> ids = new HashSet<String>();
		List<CO12Message> updts = new ArrayList<CO12Message>();
		
		if("del".equalsIgnoreCase(idsOpt.getOpt())) {
			ids = msgs.stream().map(CO12Message::getId).collect(Collectors.toSet());
			commService.deleteEntitys(msgs);
			return DataVo.Success(ids);
		}else {
			if("read".equalsIgnoreCase(idsOpt.getOpt())) {
				for(CO12Message msg : msgs) {
					msg.setRead(BoolVal.Yes.getVal());
					updts.add(msg);
					ids.add(msg.getId());
				}
			}else if("done".equalsIgnoreCase(idsOpt.getOpt())) {
				for(CO12Message msg : msgs) {
					msg.setDone(BoolVal.Yes.getVal());
					updts.add(msg);
					ids.add(msg.getId());
				}
			}
			if(commService.updateObjs(updts)) {
				return DataVo.Success(ids);
			}else {
				return DataVo.FailDB();
			}
		}
	}
}